import React, { Component } from 'react';
import { AmrnbPlayer } from 'amrnb';

class AMRPlayer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            audioBuffer: null,
            audioContext: null,
            amrnbPlayer: null,
        };
    }

    loadAMRFile = async () => {
        const { src } = this.props;
        const response = await fetch(src);
        const arrayBuffer = await response.arrayBuffer();
        const audioContext = new AudioContext();
        const amrnbPlayer = new AmrnbPlayer(audioContext);
        const buffer = await amrnbPlayer.decode(arrayBuffer);

        this.setState({
            audioBuffer: buffer,
            audioContext,
            amrnbPlayer,
        });
    };

    playAudio = () => {
        const { audioBuffer, audioContext } = this.state;
        if (audioBuffer && audioContext) {
            const source = audioContext.createBufferSource();
            source.buffer = audioBuffer;
            source.connect(audioContext.destination);
            source.start();
        }
    };

    render() {
        return (
            <div>
                <button onClick={this.loadAMRFile}>Load AMR File</button>
                <button onClick={this.playAudio} disabled={!this.state.audioBuffer}>
                    Play
                </button>
            </div>
        );
    }
}

export default AMRPlayer;
